<template>
  <el-drawer
    modal-class="lowcode-drawer"
    v-model="visible"
    append-to-body
    :close-on-click-modal="false"
    :show-close="false"
    :modal="false"
    v-bind="attr"
    @close="close"
  >
    <el-row type="flex" class="drawer-box">
      <el-scrollbar class="body-box">
        <Body :body="schema.body" />
      </el-scrollbar>
      <el-row type="flex" justify="center" align="middle" class="footer">
        <LowCode v-for="(item, index) in actions" :key="item.key || index" :schema="item" />
      </el-row>
    </el-row>
  </el-drawer>
</template>

<script setup>
import { defineProps, ref, reactive, watchEffect, provide } from 'vue'
import Body from '../body/index.vue'
import { filterAttr } from '../../common/util'
import LowCode from '@/components/LowCode.vue'

defineOptions({ name: 'DialogCom' })

defineExpose({
  show,
  hide
})

const form = reactive({})
provide('lowCodeDrawer', {
  hide,
  setForm(_form) {
    for (const [key, value] of Object.entries(_form)) {
      form[key] = value
    }
  }
})
provide('lowCodeForm', form)

const props = defineProps({
  schema: {
    type: Object,
    required: true
  }
})

const visible = ref(false)
const actions = ref(props.schema.actions || [])

const attr = ref()

watchEffect(() => {
  attr.value = filterAttr(props.schema)
  const schema = props.schema
  actions.value = []
  if (!schema.actions) {
    if (schema.cancelButton) {
      actions.value.push(schema.cancelButton)
    } else {
      actions.value.push({
        type: 'button',
        actionType: 'cancel',
        body: '取消'
      })
    }
    if (schema.confirmButton) {
      actions.value.push(schema.confirmButton)
    } else {
      actions.value.push({
        type: 'button',
        actionType: 'submit',
        level: 'primary',
        body: '确认'
      })
    }
  }
})

function show() {
  visible.value = true
}

function hide() {
  visible.value = false
}
</script>
<style lang="scss" scoped>
.drawer-box {
  height: 100%;
  flex-direction: column;
  .body-box {
    flex: 1;
    overflow-y: auto;
    padding: 10px;
    padding-top: unset;
  }
  .footer {
    padding: 10px;
    border-top: 1px solid var(--el-bg-color-page);
  }
}
</style>
<style lang="scss">
.lowcode-drawer {
  .el-drawer__header {
    padding: 10px;
    border-bottom: 1px solid var(--el-bg-color-page);
  }
  .el-drawer__body {
    padding: 0;
  }
}
</style>
